package org.jeecg.modules.bpm.util;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;

public class BpmUtil {
	
	public static String getNodeUrl(Map<String, Object> variables,String formUrl,String dataId) {
		if(oConvertUtils.isEmpty(formUrl)) {
			return null;
		}
		Set<String> varParams = getVarParams(formUrl);
		if(varParams!=null&&varParams.size()>0) {
			 formUrl = getContent(variables, formUrl);
		}else {
			if(formUrl.indexOf("/online/df/")>=0||formUrl.indexOf("/online/dfview/")>=0) {
				if(formUrl.endsWith("/")) {
					formUrl +=dataId;
				}else {
					formUrl +="/"+dataId;
				}
			}
		}
		return formUrl;
	}
	
	public static String getContent(Map<String, Object> variables,String exp){
		try {
			if(oConvertUtils.isEmpty(exp)) {
				return null;
			}
			Set<String> varParams = getVarParams(exp);
			for(String var:varParams){
				Object obj = variables.get(var);
				if(obj==null){
					obj = variables.get(var.toUpperCase());
					if(obj==null) {
						obj = "";
					}
				}else if(obj instanceof Date){
					obj = DateUtils.formatDate((Date)obj);
				}
				exp = exp.replace("${"+var+"}", obj.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return exp;
	}
	
	public static Set<String> getVarParams(String exp) {
		if(oConvertUtils.isEmpty(exp)){
			return null;
		}
		Set<String> varParams = new HashSet<String>();
		String regex = "\\$\\{\\w+\\}";
		
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(exp);
		while(m.find()){
			String var = m.group();
			varParams.add(var.substring(var.indexOf("{")+1,var.indexOf("}")));
		}
		return varParams;
	}

}
